<?php

declare(strict_types=1);

namespace App\Controller\AdminApi;

use App\Exception\XZXValidationException;
use App\Middleware\AdminApi\AdminJWTAuthMiddleware;
use App\Service\SysNodeService;
use App\Utils\CustomUtils;
use App\Utils\DateUtils;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;

/**
 * Class SysNodeController
 * @package App\Controller
 *
 * @Controller(prefix="/admin/api/sysNode")
 */
class SysNodeController extends AdminBaseController
{
    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var SysNodeService
     */
    protected $SysNodeService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function get(RequestInterface $request)
    {
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        return $this->SysNodeService->get($param);
    }

    /**
     * 编辑
     * @PostMapping(path = "edit")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function edit(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id'         => 'required|uuid',
                // 'component'  => 'sometimes|required',
                'parentId'   => 'required',
                // 'shortName'  => 'sometimes|required',
                'showStatus' => 'required|integer|max:1|min:0',
                'sort'       => 'required|integer|max:100|min:0',
                'status'     => 'required|integer|max:1|min:0',
//                'style'      => 'sometimes|required',
                'title'      => 'required',
                // 'url'        => 'sometimes|required',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        if (empty($param['parentId'])) {
            $param['parentId'] = 'root';
        }
        return $this->SysNodeService->edit($param);
    }

    /**
     * 添加
     * @PostMapping(path = "add")
     * @Middleware(AdminJWTAuthMiddleware::class) 
     */
    public function add(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                // 'component'  => 'sometimes|required',
                // 'parentId'   => 'required',
                // 'shortName'  => 'sometimes|required',
                'showStatus' => 'required|integer|max:1|min:0',
                'sort'       => 'required|integer|max:100|min:0',
                'status'     => 'required|integer|max:1|min:0',
                // 'style'      => 'sometimes|required',
                'title'      => 'required',
                // 'url'        => 'sometimes|required',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        if (empty($param['parentId'])) {
            $param['parentId'] = 'root';
        }
        return $this->SysNodeService->add($param);
    }

    /**
     * 删除
     * @PostMapping(path = "del")
     * @Middleware(AdminJWTAuthMiddleware::class) 
     */
    public function del(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        return $this->SysNodeService->del($param);
    }

    /**
     * 查询
     * @PostMapping(path = "list")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function list(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'page'               => 'required|integer|min:1',
                'limit'              => 'required|integer|min:1',
//                'search.parentId'    => 'sometimes|required|uuid',
//                'search.url'         => 'sometimes|required',
//                'search.showStatus'  => 'sometimes|required|integer|max:1|min:0',
//                'search.status'      => 'sometimes|required|integer|max:1|min:0',
//                'search.title'       => 'sometimes|required|between:1,50|alpha_num',
//                'search.parentTitle' => 'sometimes|required|between:1,50|alpha_num',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }
        
        $param = $request->all();

        if(isset($param['search'])){
            $search = $param['search'];

            CustomUtils::xzxAddSearch($param, $search, 'parentId');
            CustomUtils::xzxAddSearch($param, $search, 'parentTitle');
            CustomUtils::xzxAddSearch($param, $search, 'title');
            CustomUtils::xzxAddSearch($param, $search, 'status');
            CustomUtils::xzxAddSearch($param, $search, 'showStatus');
            CustomUtils::xzxAddSearch($param, $search, 'url');
    
            CustomUtils::xzxAddSearch($param, $search, 'createTimeRange');
            if(isset($param["createTimeRange"]))
            {
                try {
                    $param['createTimeRange'][0] = DateUtils::dateToTimeStamp($param['createTimeRange'][0]);
                    $param['createTimeRange'][1] = DateUtils::dateToTimeStamp($param['createTimeRange'][1]);
                } catch (\Throwable $th) {
                    unset($param['createTimeRange']);
                }
            }
    
        }

        
        return $this->SysNodeService->list($param);
    }
   
    /**
     * 查询
     * @PostMapping(path = "getNodeOptions")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function getNodeOptions(RequestInterface $request) {
        
        // $post = $request->post();

        $param = $request->all();
        $search = $param['search'];

        CustomUtils::xzxAddSearch($param, $search, 'status');

        return $this->SysNodeService->getNodeOptions($param);
        
    }

    /**
     * 查询菜单树形结构
     * @PostMapping(path = "getNodeTree")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function getNodeTree(RequestInterface $request) {
        return $this->SysNodeService->getNodeTree();
        
    }

    /**
     * 查询按钮树形结构
     * @PostMapping(path = "getButtonNodeTree")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function getButtonNodeTree(RequestInterface $request) {
        return  $this->SysNodeService->getButtonNodeTree();
        
    }
}